<?php

//    insert into t_user(`id`, `email`, `login`, `password`, `referal`, `dt`, `lastvisittime`) select `id`, `email`, `r`, `password`, `parent`, `regdate`, `lastcheckdate` from cabinets

    global $mikron;
    
                /*
                $win = new T_WIN();
                $win->game->value = $game->id;
                $win->winkey->value = $winkey;
                $win->Save();
                echo 'isnew=', $win->isnew?1:0;
                $win->state->value = 2;
                $win->Save();
                */

    $nalog_value = 1;

    /*$string = 'Привет, мир!';
    $f = fopen(dirname(__FILE__).'/teeeeeeeeeeest.txt', 'w');
    fwrite($f, iconv('utf-8', 'cp1251', $string));
    fclose($f);*/

    if(isset($_GET['expacketgen']))
    {
        // Генерация оплачиваемых пакетов
        try
        {
            $mob_records = Array();
            if(class_exists("EXPORT_PACKET") && class_exists("T_EX_RECORD"))
            {
                // создание поддиректорий
                $rec_dirs = Array("wm"=>dirname(__FILE__)."/wm/","mob"=>dirname(__FILE__)."/mob/");
                foreach($rec_dirs as $key=>$dirname)
                {
                    if(!file_exists($dirname))
                    {
                        mkdir($dirname, 0700);
                    }
                }           
                for($i = 1; $i <= 7; $i++)
                {
                    $mob_records = Array();
                    $wm_records = Array();
                    $tm = time() - (3600*24) * $i;
                    $day = date("d", $tm);
                    $month = date("m", $tm);
                    $year = date("Y", $tm);
                    $packet = $mikron->Queries->Query('EXPORT_PACKET', null, new Criteria(Array(new Criterion("DAY(`dt`)", $day),new Criterion("MONTH(`dt`)", $month),new Criterion("YEAR(`dt`)", $year))));
                    if($packet->count() < 1)
                    {
                        $records = $mikron->Queries->Query('T_EX_RECORD', null, new Criteria(Array(new Criterion("DAY(`dt`)", $day),new Criterion("MONTH(`dt`)", $month),new Criterion("YEAR(`dt`)", $year),new Criterion('status', 1))));
                        if($records->count() > 0)
                        {
                            $saved_items = Array();
                            $packet = new EXPORT_PACKET();
                            $packet->dt->value = date('d-m-Y', $tm);
                            $packet->operated->value = false;
                            $mikron->EntityManager->Save(Array($packet), false);
                            while($record = $records->fetch())
                            {
                                $saved_items[] = $record;
                                $record->packet->value = $packet->id;
                                $record->status->value = 5;
                                $amount = ($record->amount->value * $nalog_value) / 100;
                                $amount = str_replace(",", ".", $amount);
                                switch($record->extodevice->value) 
                                {
                                    case 1: // Webmoney
                                        $puyid = $record->id+100000000;
                                        $extonumber = $record->extonumber->value;
                                        $wm_records[] = "$extonumber;$amount;Вывод с проекта 7шансов;$puyid";
                                        break;
                                    case 2: // mobile phone
                                        $provider = (int)$record->provider->value->code->value;
                                        $extonumber = $record->extonumber->value;
                                        $mob_records[] = "$extonumber;$provider;$amount;WMR;Вывод с проекта 7шансов";
                                        break;
                                }
                            }

                            $file_devices = Array("wm"=>$wm_records, "mob"=>$mob_records);
                            $archfiles = Array();

                            foreach($file_devices as $prefix => $devrecords)
                            {
                                // сохранение в файл
                                $f = null;
                                // сохранение выплат на мобилки в файлы
                                $cnt = 0;
                                $fileindex = 0;
                                foreach($devrecords as $rec)
                                {
                                    if($cnt % 5 == 0)
                                    {
                                        if(!is_null($f)){fclose($f);}
                                        $fileindex++;
                                        $mi = $prefix.substr("000".$fileindex, -4);
                                        $dtmask = date("d-m-Y", $tm);
                                        $filename = $rec_dirs[$prefix].$dtmask."_$mi.csv";
                                        if(file_exists($filename)){unlink($filename);}
                                        $f = fopen($filename, "w");
                                        $archfiles[] = str_replace("\\", "/", realpath($filename));
                                    }
                                    fwrite($f, iconv('utf-8', 'cp1251', $rec)."\r\n");
                                    $cnt++;
                                }
                                if(!is_null($f))
                                {
                                    fclose($f);
                                }
                            }

                            $archive_filename = str_replace("\\", "/", dirname(__FILE__)."/".date("d-m-Y", $tm).".zip");
                            if(file_exists($archive_filename))
                            {
                                unlink($archive_filename);
                            }
                            // Load module PCLZip
                            $mikron->Modules->LoadModule('pclzip');
                            $ziparchive = new PclZip($archive_filename);
                            $list = $ziparchive->create(implode(",", $archfiles), PCLZIP_OPT_REMOVE_PATH, dirname(__FILE__)."/");
                            // $list = $ziparchive->create(implode(",", $archfiles), PCLZIP_OPT_REMOVE_ALL_PATH);
                            if($list == 0)
                            {
                                echo "ERROR : ".$ziparchive->errorInfo(true);
                            }
                            else
                            {
                                foreach($archfiles as $afile)
                                {
                                    unlink($afile);
                                }
                                $packet->file->value = '/adminpanel/'.basename($archive_filename);
                                $saved_items[] = $packet;
                                $mikron->EntityManager->Save($saved_items);
                            }
                        }
                    }
                }
            }
        }
        catch(Exception $ex)
        {
            echo $ex->getMessage();
        }
    }

    // Управление пакетами оплат
    ?><h1>Пакеты оплат:</h1><?php
    if(isset($_POST['selectedpackets']))
    {
        $ids = $_POST['selectedpackets'];
        $items = $mikron->Queries->Query("EXPORT_PACKET", $ids, "`operated`=0 or `operated` IS NULL");
        $saveditems = Array();
        while($item = $items->fetch())
        {
            while($record = $item->records->value->fetch())
            {
                $record->status->value = 2;
                $saveditems[] = $record;
            }
            $item->operated->value = 1;
            $saveditems[] = $item;
        }
        $mikron->EntityManager->Save($saveditems);
    }
    $packets = $mikron->Queries->Query("EXPORT_PACKET", null, "`operated` = 0 OR `operated` IS NULL");
    if($packets->count() == 0)
    {
        ?>Пакетов нет<?php
    }
    else
    {
        $frm = new html_form("packetsopers", "post", "/");
            $tbl = new html_table(null, "table3", null, 0, 4);
                $tbl->addhead("&nbsp;");
                $tbl->addhead("Дата");
                $tbl->addhead("Записей");
                $tbl->addhead("Сумма");
                $tbl->addhead("Архив");
                $packet = new EXPORT_PACKET();
                while($packet = $packets->fetch())
                {
                    $id = $packet->id;
                    // $tbl->newrow();
                    $tbl->newcol(null,false,true,null,null,"4");
                        ?><input type="checkbox" name="selectedpackets[]" value="<?php echo $id; ?>"><?php   
                    $tbl->newcol(MikronDateTime::BeautifulDate(strtotime($packet->dt->value), false));
                    $tbl->newcol($packet->records->value->count());
                    $summa = 0;
                    $record = new T_EX_RECORD();
                    while($record = $packet->records->value->fetch())
                    {
                        $summa += $record->amount->value;
                    }
                    $tbl->newcol(round(($summa) / 100, 2).' руб.', true);
                    $tbl->newcol();
                        ?><a href="<?php echo $packet->file->value; ?>">Скачать</a><?php
                }
            $tbl->end();
            ?><br /><input type="submit" value="Оплатил выбранные"><?php
        $frm->end();
    }
    ?><br /><a href="/?expacketgen">Сгенерировать пакеты</a><?php

    /**
    * Обнуление проекта
    */
    if(isset($_GET['clearproject']))
    {
        if($mikron->ACL->hasRole('admin'))
        {
            try
            {
                // mysql_query('DELETE FROM T_USER where `id` > 3');
                mysql_query('UPDATE T_USER SET `amount` = 0, `winamount` = 0');
                mysql_query('DELETE FROM T_USERS_ROLES where `user` > 3');
                mysql_query('UPDATE GAME SET `bank` = 0, `churkasaloed` = 0');
                mysql_query('ALTER TABLE T_USER auto_increment = 4;');
                $mikron->EntityManager->DeleteEntity('T_OPERATIONS_LOG', '*', true);
                $mikron->EntityManager->DeleteEntity('MANUAL_TRANSFER', '*', true);
                $mikron->EntityManager->DeleteEntity('T_WIN', '*', true);
                $mikron->EntityManager->DeleteEntity('PLAYLOG', '*', true);
                $mikron->EntityManager->DeleteEntity('T_EX_RECORD', '*', true);
                $mikron->EntityManager->DeleteEntity('EXPORT_PACKET', '*', true);
                $mikron->EntityManager->DeleteEntity('T_ORDER', '*', true);
                echo '<p>Проект успешно обнулен.</p>';
            }
            catch(Exception $ex)
            {
                echo 'Ошибка: ', $ex->getMessage();
            }
        }
    }
?>

<p>
    <div id="nullproject0" style=" padding: 0em; ">
    <a href="#clearproject" onclick="nullproject1.style.display='';">Обнулить проект</a>
    <div id="nullproject1" style="display: none; padding: 1em; "><a href="#clearproject" onclick="nullproject2.style.display='';">Уверен?</a>
    <div id="nullproject2" style="display: none; padding: 1em; "><a href="#clearproject" onclick="nullproject3.style.display='';">Фсё пропадет</a>
    <div id="nullproject3" style="display: none; padding: 1em; "><a href="/?clearproject">Подтверждаю!</a></div></div>
    </div>
</p>